import React, { useState } from 'react'
import './index.css'

export default function Item({ todo, done, todoList, setTodoList, id }) {
  //isActive用来li的active类和删除按钮的显示隐藏的类
  const [isActive, setIsActive] = useState(false)

  //鼠标移入和移出li的函数用来接受参数
  const mouseHandle = (bool) => {
    //返回的这个函数才是真正的事件函数
    return () => {
      setIsActive(bool)
    }
  }


  //多选框改变触发的事件函数
  const checkChangeHandle = (e) => {
    const newTode = todoList.map((item) => {
      //如果点击的item的id和todoList中的id相等那么就改变todoList中对应的done取反
      if(item.id === id){
        return {...item , done : e.target.checked}
      }
      return {...item}
    })

    setTodoList(newTode)
  }


  //删除逻辑
  const deleteHandle = (e) => {
    const newTode = todoList.filter(item => {
      return item.id !== id
    })

    setTodoList(newTode)
  }

  return (
    <li
      onMouseEnter={mouseHandle(true)}
      onMouseLeave={mouseHandle(false)}
      className={isActive ? "active" : ""}
    >
      <label>
        <input type="checkbox" checked={done} onChange={checkChangeHandle} />
        <span>{todo}</span>
      </label>
      <button 
        className="btn btn-danger" 
        style={{ display: isActive ? "block" : "none" }}
        onClick = {deleteHandle}
      >删除</button>
    </li>
  )
}
